/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.web.web;

import com.google.common.collect.Lists;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.modules.web.entity.WxCombination;
import com.jeeplus.modules.web.service.WxAgentsService;
import com.jeeplus.modules.web.service.WxCombinationService;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import java.util.List;
import java.util.Map;

/**
 * 预购开机Controller
 * @author rongjie
 * @version 2017-08-06
 */
@Controller
@RequestMapping(value = "${adminPath}/web/wxCombination")
public class WxCombinationController extends BaseController {

	@Autowired
	private WxCombinationService wxCombinationService;
	@Autowired
	private WxAgentsService wxAgentsService;

	@ModelAttribute
	public WxCombination get(@RequestParam(required=false) String id) {
		WxCombination entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = wxCombinationService.get(id);
		}
		if (entity == null){
			entity = new WxCombination();
		}
		return entity;
	}

	/**
	 * 预购开机列表页面
	 */
	@RequiresPermissions("web:wxCombination:list")
	@RequestMapping(value = {"list", ""})
	public String list() {
		return "modules/web/wxCombinationList";
	}

		/**
	 * 预购开机列表数据
	 */
	@ResponseBody
	@RequiresPermissions("web:wxCombination:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(WxCombination wxCombination, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<WxCombination> page = wxCombinationService.findPage(new Page<WxCombination>(request, response), wxCombination);
		return getBootstrapData(page);
	}

	/**
	 * 查看，增加，编辑预购开机表单页面
	 */
	@RequiresPermissions(value={"web:wxCombination:view","web:wxCombination:add","web:wxCombination:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(WxCombination wxCombination, Model model) {
		model.addAttribute("wxCombination", wxCombination);
		if(StringUtils.isBlank(wxCombination.getId())){//如果ID是空为添加
			model.addAttribute("isAdd", true);
		}
		return "modules/web/wxCombinationForm";
	}

	/**
	 * 保存预购开机
	 */
	@RequiresPermissions(value={"web:wxCombination:add","web:wxCombination:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(WxCombination wxCombination, Model model, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, wxCombination)){
			return form(wxCombination, model);
		}
		if(!StringUtils.isEmpty(wxCombination.getUrl())){

			String tempImg=Global.getConfig("url")+(wxCombination.getUrl().replace("|","").replace( Global.getConfig("url"),"").trim()) ;
			//新部署的环境，url有重复的jeeplus。此修改兼容两套环境，避免配置修改
			String img=tempImg.replace("/jeeplus/jeeplus/", "/jeeplus/") ;
			wxCombination.setUrl(img);
		}
		//新增或编辑表单保存
		wxCombinationService.save(wxCombination);//保存
		addMessage(redirectAttributes, "保存预购开机成功");
		return "redirect:"+Global.getAdminPath()+"/web/wxCombination/?repage";
	}

	/**
	 * 删除预购开机
	 */
	@ResponseBody
	@RequiresPermissions("web:wxCombination:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(WxCombination wxCombination, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		wxCombinationService.delete(wxCombination);
		j.setMsg("删除预购开机成功");
		return j;
	}

	/**
	 * 批量删除预购开机
	 */
	@ResponseBody
	@RequiresPermissions("web:wxCombination:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			wxCombinationService.delete(wxCombinationService.get(id));
		}
		j.setMsg("删除预购开机成功");
		return j;
	}

	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("web:wxCombination:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public AjaxJson exportFile(WxCombination wxCombination, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "预购开机"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<WxCombination> page = wxCombinationService.findPage(new Page<WxCombination>(request, response, -1), wxCombination);
    		new ExportExcel("预购开机", WxCombination.class).setDataList(page.getList()).write(response, fileName).dispose();
    		j.setSuccess(true);
    		j.setMsg("导出成功！");
    		return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出预购开机记录失败！失败信息："+e.getMessage());
		}
			return j;
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("web:wxCombination:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<WxCombination> list = ei.getDataList(WxCombination.class);
			for (WxCombination wxCombination : list){
				try{
					wxCombinationService.save(wxCombination);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条预购开机记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条预购开机记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入预购开机失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/web/wxCombination/?repage";
    }

	/**
	 * 下载导入预购开机数据模板
	 */
	@RequiresPermissions("web:wxCombination:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "预购开机数据导入模板.xlsx";
    		List<WxCombination> list = Lists.newArrayList();
    		new ExportExcel("预购开机数据", WxCombination.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/web/wxCombination/?repage";
    }



}